/**
 * BrandBigData.com Inc. Copyright (c) 2018 All Rights Reserved.
 */
package com.qibao.toolkit.conf;

import com.qibao.toolkit.LocalPythonExecutorService;
import com.qibao.toolkit.PythonExecutorFactory;
import com.qibao.toolkit.PythonExecutorPool;
import com.qibao.toolkit.RemotePythonExecutorService;
import com.qibao.toolkit.facade.PythonExecutorService;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @author wangcong
 * @version $Id: PythonServiceConf.java, v0.1 2018/5/31 18:52 wangcong Exp $$
 */
@Configuration
public class PythonServiceConf {

    private static final Logger logger = LoggerFactory.getLogger(PythonServiceConf.class);

    @Autowired
    private Environment environment;


    @Value("${plutus.python.service.maxTotal:5}")
    private int poolMaxTotal;

    /**
     * 优先创建远程服务
     */
    @Bean
    @ConditionalOnProperty(name = "python.service.url")
    public PythonExecutorService remotePythonExecutorService() {
        String pythonServiceUrl
                = environment.getProperty("python.service.url");
        logger.info("create PythonExecutorService instance with remote python service, url: {}",
                pythonServiceUrl);
        return new RemotePythonExecutorService(pythonServiceUrl);
    }

    @Bean
    @ConditionalOnMissingBean(value = PythonExecutorService.class)
    public PythonExecutorFactory pythonExecutorFactory() {
        return new PythonExecutorFactory();
    }

    @Bean
    @ConditionalOnMissingBean(value = PythonExecutorService.class)
    public PythonExecutorPool pythonExecutorPool(PythonExecutorFactory pythonExecutorFactory) {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(poolMaxTotal);
        poolConfig.setJmxEnabled(false);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnCreate(true);
        poolConfig.setMaxIdle(poolMaxTotal + 1);
        poolConfig.setTimeBetweenEvictionRunsMillis(-1L);
        return new PythonExecutorPool(pythonExecutorFactory, poolConfig);
    }

    @Bean
    @ConditionalOnMissingBean(value = PythonExecutorService.class)
    public PythonExecutorService localPythonExecutorService(PythonExecutorPool pythonExecutorPool) {
        
        logger.info("create PythonExecutorService instance on local");
        return new LocalPythonExecutorService(pythonExecutorPool);
    }





}
